<?php
	function check_option($opt){
	  if(isset($opt) && !empty($opt))
	      return true;
	    else
	      return false;
	}
	
	function is_json($string){
		// Check argument is a json or not.
		return (is_string($string) && is_object(json_decode($string))) ? true : false;
	}
   
	function redirect_to($page, $path=""){
		$full_path = rtrim($path, "/") . "/" . $page;
		return "header('Location: ". $full_path . "');";
	}
	
	function handle_fields($ary){
	// For update_fields
	  $str = "";
	  foreach($ary as $key => $value){
		  $str.=$key."='".$value."',";
		}
	  return rtrim($str, ",");
	}
	
	function handle_fields_and_values($array){
  // For create
	  $f = "";
	  $v = "";
	  foreach($array as $field => $value){
		  $f.= "`".$field."`,";
		  $v.= "'".$value."',";
		}
	  $f = rtrim($f, ",");
	  $v = rtrim($v, ",");
	  return "(" . $f . ")_S_(" . $v . ")";
	}
	
	function parse_options($from, $hash){
		// For find_all, find_all_by_fields
		if(check_option($hash["select"]))
	    $select = " " . $hash["select"] . " ";
	  else
	    $select = " * ";

	  if(check_option($hash["conditions"]))
	    $where.= " WHERE " . $hash["conditions"] . " ";

	  if(check_option($hash["order"]))
	    $order = " ORDER BY ".$hash["order"]." ";

	  if(check_option($hash["group"]))
	    $group = " GROUP BY ".$hash["group"]." ";

	  // 2008.02.15
	  // Limit位置修正
	  if(check_option($hash["limit"]))
	    $limit = " LIMIT ".$hash["limit"]." ";

	  if(check_option($hash["limit"]) && check_option($hash["offset"]))
	    $offset = "OFFSET ".$hash["offset"]." ";

		$sql = "SELECT";
		$sql.= $select;
		$sql.= " FROM ".$from;
		$sql.= $where;
		// 2008.02.25
		// Group By位置修正
		$sql.= $group;
		$sql.= $order;
		$sql.= $limit;
		$sql.= $offset;
		return $sql;
	}
?>